import qs from '../miniprogram_npm/qs/index'
const _baseUrl = () => {
  const {
    miniProgram: {
      envVersion
    }
  } = wx.getAccountInfoSync()
  const urlObj = {
    develop: {
      baseUrl: "http://internet-hospital.whmdtechnology.com",
      wsUrl: "ws://internet-hospital.whmdtechnology.com:2347"
      // baseUrl: "https://hlwyy.hbjsxrmyy.com",
      // wsUrl: "wss://hlwyy.hbjsxrmyy.com/wss"
    }, //开发
    trial: {
      baseUrl: "https://hlwyy.hbjsxrmyy.com",
      wsUrl: "wss://hlwyy.hbjsxrmyy.com/wss"
    }, //体验
    release: {
      baseUrl: "https://hlwyy.hbjsxrmyy.com",
      wsUrl: "wss://hlwyy.hbjsxrmyy.com/wss"
    }, //线上
  }
  if (envVersion === "develop") {
    return urlObj.develop
  }
  return urlObj[envVersion]
}


const {
  baseUrl,
  wsUrl
} = _baseUrl()


var tokenInvalid = false
const http = ({
  url = '',
  param = {},
  ...other
} = {}) => {
  // wx.showLoading({
  //     title: '请求中，请耐心等待..'
  // });
  let timeStart = Date.now();
  return new Promise((resolve, reject) => {
    // 判断当前的路由
    const token = wx.getStorageSync('token')
    let pages = getCurrentPages()
    // 如果没有token，并且还不是登录界面

    wx.request({
      url: getUrl(url),
      data: param,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Accept': 'application/json, text/plain, */*',
        'content-type': 'application/x-www-form-urlencoded' // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded"
      },
      ...other,
      complete: (res) => {
        // console.log(res)
        var tokenFlag = 0
        if (res.data && res.data.code == 200 && res.data.status == 'success') {
          tokenFlag = 0
          resolve(res.data)
        } else {
          if (res.data && res.data.message == "登录信息失效，请退出后重新登录") {
            if (tokenInvalid) return
            tokenInvalid = true
            let pages = getCurrentPages() //获取加载的页面
            let path = pages[pages.length - 1]
            let url = ''
            let query = ""
            if (path.options) {
              query = qs.stringify(path.options)

            }
            if (query != '') {
              url = `/${path.route}?${query}`
            } else {
              url = `/${path.route}`
            }
            wx.setStorage({
              key: "fromUrl",
              data: url
            })
            wx.showModal({
              title: "登录信息失效，请退出后重新登录",
              success() {
                tokenInvalid = false
                wx.removeStorage({
                  key: 'token',
                  success() {
                    wx.reLaunch({
                      url: "pages/login/login",
                    })
                  }
                })

              }
            })
            reject(res)
            return
          } else if (res.data && res.data.code == 402) {
            reject(res.data)
            return
          } else if (res.data.message === 'This action is unauthorized.') {
            wx.showModal({
              title: "身份过期，请重新登录",
              success() {
                wx.removeStorage({
                  key: 'token',
                  success() {
                    wx.reLaunch({
                      url: "/pages/login/index",
                    })
                  }
                })

              }
            })
          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'error'
            })
          }
          reject(res.data || {})
        }
      }
    })




  })
}








// 解析 SSE 数据
function parseSSE(chunk) {
  let buffer = '';
  let arr = ''
  /*   const decoder = new TextDecoder();
    buffer += decoder.decode(chunk, {
      stream: true
    }); */
    //真机上面进行使用
  buffer += arrayBufferToString(chunk)
  const lines = buffer.split('\n');
  buffer = lines.pop() || '';

  lines.forEach(line => {
    if (!line.trim()) return; // 跳过空行

    const [field, value] = line.split(': ', 2);
    if (field === 'data' && value) {
      arr += JSON.parse(value).content
    }
  });
  return arr
}

function arrayBufferToString(arr) {

  if (typeof arr === 'string') {

    return arr;
  }
  var dataview = new DataView(arr);
  var ints = new Uint8Array(arr.byteLength);
  for (var i = 0; i < ints.length; i++) {

    ints[i] = dataview.getUint8(i);
  }
  var str = '',
    _arr = ints;
  for (var i = 0; i < _arr.length; i++) {

    if (_arr[i]) {

      var one = _arr[i].toString(2),
        v = one.match(/^1+?(?=0)/);
      if (v && one.length == 8) {

        var bytesLength = v[0].length;
        var store = _arr[i].toString(2).slice(7 - bytesLength);
        for (var st = 1; st < bytesLength; st++) {

          if (_arr[st + i]) {

            store += _arr[st + i].toString(2).slice(2);
          }
        }
        str += String.fromCharCode(parseInt(store, 2));
        i += bytesLength - 1;
      } else {

        str += String.fromCharCode(_arr[i]);
      }
    }
  }
  return str;
}


// 发起请求
const requestTask = ({
  url = '',
  param = {},
} = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: getUrl(url),
      method: 'POST',
      data: param,
      header: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream',
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
      },
      responseType: 'arraybuffer',
      complete: (res) => {
        let val = parseSSE(res.data);
        resolve(val)
      },

      fail: (err) => {
        console.log(err)
      }
    })
  })
}




const getUrl = (url) => {
  if (url.indexOf('://') == -1) {
    url = baseUrl + url;
  }
  return url
}

// get方法
const get = (url, param = {}) => {
  let urlQueryString = qs.stringify(param, { //使用到qs ,先下载，后引入
    addQueryPrefix: true,
    allowDots: true,
  });
  url = `${url}?${urlQueryString}`
  return http({
    url
  })
}


const post = (url, param = {}) => {
  return http({
    url,
    param: qs.stringify(param),
    method: 'post'
  })
}

const put = (url, param = {}) => {
  return http({
    url,
    param: qs.stringify(param),
    method: 'put'
  })
}

const del = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'delete'
  })
}
const dep = (url, param = {}) => {
  return requestTask({
    url,
    param: param,
  })
}
module.exports = {
  get,
  post,
  put,
  del,
  baseUrl,
  wsUrl,
  dep
}